<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class comment extends core {

	public function __construct() {
		parent::__construct();
	}

	//列出商品评价
	public function index() {
		$goods_id = (isset($_GET['goods_id']) && trim($_GET['goods_id'])) ? intval($_GET['goods_id']) : 0;
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$sql = "SELECT comment_time, comment_stars, comment_content, m.name as member_name,m.nick_name as
			member_nick_name, m.avatar as member_avatar
			FROM {$this->tbp}order_goods og LEFT JOIN {$this->tbp}member m ON og.member_id=m.id
			WHERE goods_id='{$goods_id}' AND comment_time>0 ORDER BY comment_time DESC
			LIMIT {$offset}, {$pagesize}";
		$comments = $this->db->get_results($sql);
		if ($comments) {
			foreach ($comments as $key => $comment) {
				$comments[$key]->comment_time = date("Y-m-d H:i:s", $comment->comment_time);
				if(preg_match("/^1[34578]\d{9}$/", $comment->member_name)){
					$comment->member_name = substr_replace($comment->member_name,'*****',3,-3);
				}
			}
		}
		success($comments);
	}

	//发表评价
	public function post() {
		$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
		$goods_id = (isset($_POST['goods_id']) && trim($_POST['goods_id'])) ? intval($_POST['goods_id']) : 0;
		$stars = isset($_POST['stars']) ? intval($_POST['stars']) : 5;
		$content = (isset($_POST['content']) && trim($_POST['content'])) ? trim($_POST['content']) : '';
		$sql = "SELECT og.id FROM {$this->tbp}order_goods og INNER JOIN {$this->tbp}order o ON og.order_id=o.id WHERE
			og.order_id='{$order_id}' AND og.goods_id='{$goods_id}' AND o.member_id='{$this->member_id}'";
		$order_goods_id = intval($this->db->get_var($sql));
		if ($order_goods_id) {
			$sql = "UPDATE {$this->tbp}order_goods SET comment_stars='{$stars}', comment_time='".time()."', comment_content='{$content}' 
				WHERE id='{$order_goods_id}'";
			$this->db->query($sql);
			//增加商品评论数
			$sql = "SELECT count(*) FROM {$this->tbp}order_goods WHERE goods_id='{$goods_id}' AND comment_time>0";
			$comments = intval($this->db->get_var($sql));
			$sql = "UPDATE {$this->tbp}goods SET comments='{$comments}' WHERE id='{$goods_id}'";
			$this->db->query($sql);
			//一个订单只要评价过一个商品，即可认为该订单被评价过
			$sql = "UPDATE {$this->tbp}order SET status='4' WHERE id='{$order_id}'";
			$this->db->query($sql);
		}
		success("ok");
	}

}
